// pages/personalinfo/personalinfo.js
import { ajax, src, util } from "../../utils/util.js";
var address = require("../../mock.js")
Page({

  /**
   * 页面的初始数据
   */
  /**
    * 控件当前显示的数据
    * provinces:所有省份
    * citys 选择省对应的所有市,
    * areas 选择市对应的所有区
    * areaInfo：点击确定时选择的省市县结果
    * animationAddressMenu：动画
    * addressMenuIsShow：是否可见
    */
  data: {
    uqid:'',
    name:'',//姓名
    date: '',//生日
    animationAddressMenu: {},
    addressMenuIsShow: false,
    value: [0, 0, 0],
    provinces: [],
    citys: [],
    areas: [],
    areaInfo: '',
    actionSheetHidden: false,//性别遮罩层
    actionSheetItems: ['男', '女'],
    sex:'',
    shebaoka:''
  },


  /**
   * 生命周期函数--监听页面加载
   */
  tobind(){
    wx.navigateTo({
      url: '../bindybk/bindybk',
    })
  },
  onLoad: function (options) {
    // 默认联动显示北京
    var id = address.provinces[0].id
    this.setData({
      provinces: address.provinces,
      citys: address.citys[id],
      areas: address.areas[address.citys[id][0].id],
    });

    var uqid = wx.getStorageSync("uqid");
    this.setData({
      uqid: uqid
    });
    this.getInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
 

  //获取个人信息
  getInfo: function () {
    ajax("/api/index/user_info", {
      data: {
        uqid: this.data.uqid,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res);
      if (res.error == 0) {
        this.setData({
          userinfo: res.data,
        })
        this.getsbk()
      }
    })
  },

   //获个人社保卡
   getsbk: function () {
    ajax("/api/index/social_card_show", {
      data: {
        uqid: this.data.uqid,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
    }, res => {
      console.log(res);
      if (res.error == 0) {
        this.setData({
          shebaoka: res.data,
        })
      }
    })
  },
  //更换头像
  replaceHead: function () {
    var that = this;
    var uqid = this.data.uqid;
    wx.showActionSheet({
      itemList: ['从相册选取', '拍照'],
      success(res) {
        var index = res.tapIndex;
        if(index == 0){
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album'],
            success(res) {
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths;
              wx.uploadFile({
                url: src + '/api/index/user_info_edit',
                filePath: tempFilePaths[0],
                name: 'avatar',
                header: { "Content-Type": "multipart/form-data" },
                formData: {
                  uqid: uqid,
                },
                success(resU) {
                  // console.log(JSON.parse(resU.data))
                  if (JSON.parse(resU.data).error == 0){
                    that.getInfo();
                    wx.showToast({
                      title: '上传成功',
                      icon:'none',
                      duration:1000
                    })
                  }

                }
              })
            }
          })
        }else if(index == 1){
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['camera'],
            success(res) {
              // tempFilePath可以作为img标签的src属性显示图片
              const tempFilePaths = res.tempFilePaths;
              wx.uploadFile({
                url: src + '/api/index/user_info_edit',
                filePath: tempFilePaths[0],
                name: 'avatar',
                header: { "Content-Type": "multipart/form-data" },
                formData: {
                  uqid: uqid,
                },
                success(resU) {
                  // console.log(JSON.parse(resU.data))
                  if (JSON.parse(resU.data).error == 0) {
                    that.getInfo();
                    wx.showToast({
                      title: '上传成功',
                      icon: 'none',
                      duration: 1000
                    })
                  }
                }
              })
            }
          })
        }

      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
    
  },


  //修改姓名
  modifyName:function(e){
    this.setData({
      name: e.detail.value
    });
    ajax("/api/index/user_info_edit", {
      data: {
        uqid: this.data.uqid,
        name: this.data.name
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method:'POST'
    }, res => {
      // console.log(res);
      if (res.error == 0) {
        this.getInfo();
      }
    })
  },
  //修改手机号码
  modifyPhone:function(){
    wx.redirectTo({
      url: '/pages/modifyphone/modifyphone',
    })
  },
  //性别
  changeTap: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  actionSheetTap: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  clickSex: function (e) {
    var selectsex = e.currentTarget.dataset.selectsex;
    this.setData({
      sex: selectsex,
      actionSheetHidden: false
    });
    var sexIndex;
    if (selectsex == '男'){
      sexIndex = 1;
    } else if (selectsex == '女'){
      sexIndex = 2;
    }

    ajax("/api/index/user_info_edit", {
      data: {
        uqid: this.data.uqid,
        sex: sexIndex //（1-男 2-女）
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'POST'
    }, res => {
      // console.log(res);
      if (res.error == 0) {
        this.getInfo();
        wx.showToast({
          title: '修改成功！',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },
  
  // 生日
  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
    ajax("/api/index/user_info_edit", {
      data: {
        uqid: this.data.uqid,
        birthday: this.data.date
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'POST'
    }, res => {
      // console.log(res);
      if (res.error == 0) {
        this.getInfo();
        wx.showToast({
          title: '修改成功！',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },


  // 点击所在地区弹出选择框
  select: function (e) {
    // 如果已经显示，不在执行显示动画
    if (this.data.addressMenuIsShow) {
      return false
    } else {
      // 执行显示动画
      this.startAddressAnimation(true)
    }
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      this.animation.translateY(0 + 'vh').step()
    } else {
      this.animation.translateY(100 + 'vh').step()
    }
    this.setData({
      animationAddressMenu: this.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  
  // 点击地区选择取消按钮
  cityCancel: function (e) {
    this.startAddressAnimation(false)
  },
  // 点击地区选择确定按钮
  citySure: function (e) {
    var that = this
    var city = that.data.city
    var value = that.data.value
    this.startAddressAnimation(false)
    // 将选择的城市信息显示到输入框
    var areaInfo = that.data.provinces[value[0]].name + '·' + that.data.citys[value[1]].name + '·' + that.data.areas[value[2]].name
    that.setData({
      areaInfo: areaInfo,
    })

    var city_name;
    if (that.data.citys[value[1]].name == '市辖区' || that.data.citys[value[1]].name == '县'){
      city_name = that.data.areas[value[2]].name;
    }else{
      city_name = that.data.citys[value[1]].name;
    }

    ajax("/api/index/user_info_edit", {
      data: {
        uqid: this.data.uqid,
        province_name: that.data.provinces[value[0]].name,
        city_name: city_name,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'POST'
    }, res => {
      // console.log(res);
      if (res.error == 0) {
        this.getInfo();
        wx.showToast({
          title: '修改成功！',
          icon: 'none',
          duration: 1000
        })
      }
    })

  },
  // 处理省市县联动逻辑
  cityChange: function (e) {
    var value = e.detail.value
    var provinces = this.data.provinces
    var citys = this.data.citys
    var areas = this.data.areas
    var provinceNum = value[0]
    var cityNum = value[1]
    var countyNum = value[2]
    // 如果省份选择项和之前不一样，表示滑动了省份，此时市默认是省的第一组数据，
    if (this.data.value[0] != provinceNum) {
      var id = provinces[provinceNum].id
      this.setData({
        value: [provinceNum, 0, 0],
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id],
      })
    } else if (this.data.value[1] != cityNum) {
      // 滑动选择了第二项数据，即市，此时区显示省市对应的第一组数据
      var id = citys[cityNum].id
      this.setData({
        value: [provinceNum, cityNum, 0],
        areas: address.areas[citys[cityNum].id],
      })
    } else {
      // 滑动选择了区
      this.setData({
        value: [provinceNum, cityNum, countyNum]
      })
    }
  },
  onShow: function () {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'linear',
    })
    this.animation = animation

    this.getInfo();
  }


})